// Unitree RL Sim2Sim Demo 前端应用
class Sim2SimDemo {
    constructor() {
        this.apiBase = 'http://localhost:8000';
        this.ws = null;
        this.isRunning = false;
        this.chart = null;
        this.chartData = {
            labels: [],
            velocity: [],
            energy: []
        };
        
        this.init();
    }

    async init() {
        await this.checkBackend();
        this.initChart();
        this.loadReports();
        this.setupWebSocket();
        this.startStatusPolling();
    }

    async checkBackend() {
        try {
            const response = await axios.get(`${this.apiBase}/`);
            console.log('后端连接成功:', response.data);
        } catch (error) {
            console.error('无法连接到后端:', error);
            this.showAlert('无法连接到后端服务，请确保后端已启动', 'danger');
        }
    }

    initChart() {
        const ctx = document.getElementById('performanceChart').getContext('2d');
        this.chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: '速度 (m/s)',
                        data: [],
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4
                    },
                    {
                        label: '能耗',
                        data: [],
                        borderColor: '#f093fb',
                        backgroundColor: 'rgba(240, 147, 251, 0.1)',
                        tension: 0.4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    setupWebSocket() {
        try {
            this.ws = new WebSocket(`ws://localhost:8000/ws/simulation`);
            
            this.ws.onopen = () => {
                console.log('WebSocket连接已建立');
            };
            
            this.ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (data.type === 'status_update') {
                    this.updateMetrics(data.data);
                }
            };
            
            this.ws.onclose = () => {
                console.log('WebSocket连接已关闭');
            };
            
            this.ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
            };
        } catch (error) {
            console.error('WebSocket连接失败:', error);
        }
    }

    async startSimulation() {
        try {
            const response = await axios.post(`${this.apiBase}/api/simulation/start`, {});
            this.isRunning = true;
            this.updateUI();
            this.showAlert('仿真已启动', 'success');
        } catch (error) {
            console.error('启动仿真失败:', error);
            this.showAlert('启动仿真失败', 'danger');
        }
    }

    async stopSimulation() {
        try {
            const response = await axios.post(`${this.apiBase}/api/simulation/stop`, {});
            this.isRunning = false;
            this.updateUI();
            this.showAlert('仿真已停止', 'info');
        } catch (error) {
            console.error('停止仿真失败:', error);
            this.showAlert('停止仿真失败', 'danger');
        }
    }

    async getStatus() {
        try {
            const response = await axios.get(`${this.apiBase}/api/simulation/status`);
            return response.data;
        } catch (error) {
            console.error('获取状态失败:', error);
            return null;
        }
    }

    updateMetrics(data) {
        // 更新数值显示
        document.getElementById('stepCount').textContent = data.step_count || 0;
        document.getElementById('velocity').textContent = (data.velocity || 0).toFixed(2);
        document.getElementById('energy').textContent = (data.energy || 0).toFixed(2);
        document.getElementById('reward').textContent = (data.total_reward || 0).toFixed(2);

        // 更新图表
        const now = new Date();
        const timeLabel = now.toLocaleTimeString();
        
        this.chartData.labels.push(timeLabel);
        this.chartData.velocity.push(data.velocity || 0);
        this.chartData.energy.push(data.energy || 0);

        // 保持数据点数量
        if (this.chartData.labels.length > 50) {
            this.chartData.labels.shift();
            this.chartData.velocity.shift();
            this.chartData.energy.shift();
        }

        this.chart.data.labels = this.chartData.labels;
        this.chart.data.datasets[0].data = this.chartData.velocity;
        this.chart.data.datasets[1].data = this.chartData.energy;
        this.chart.update('none');
    }

    updateUI() {
        const statusIndicator = document.getElementById('statusIndicator');
        const statusText = document.getElementById('statusText');
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');

        if (this.isRunning) {
            statusIndicator.className = 'status-indicator status-running';
            statusText.textContent = '运行中';
            startBtn.disabled = true;
            stopBtn.disabled = false;
        } else {
            statusIndicator.className = 'status-indicator status-stopped';
            statusText.textContent = '已停止';
            startBtn.disabled = false;
            stopBtn.disabled = true;
        }
    }

    async loadReports() {
        try {
            const response = await axios.get(`${this.apiBase}/api/reports`);
            const reports = response.data.reports || [];
            this.displayReports(reports);
        } catch (error) {
            console.error('加载报告失败:', error);
        }
    }

    displayReports(reports) {
        const container = document.getElementById('reportsList');
        
        if (reports.length === 0) {
            container.innerHTML = '<p class="text-muted text-center">暂无实验报告</p>';
            return;
        }

        const html = reports.map(report => `
            <div class="d-flex justify-content-between align-items-center mb-2 p-3 bg-light rounded">
                <div>
                    <h6 class="mb-1">${report.title}</h6>
                    <small class="text-muted">${new Date(report.timestamp).toLocaleString()}</small>
                </div>
                <div>
                    <button class="btn btn-sm btn-outline-primary" onclick="downloadReport('${report.id}')">
                        <i class="fas fa-download"></i> 下载
                    </button>
                </div>
            </div>
        `).join('');

        container.innerHTML = html;
    }

    generateReport() {
        const modal = new bootstrap.Modal(document.getElementById('reportModal'));
        modal.show();
    }

    async submitReport() {
        const title = document.getElementById('reportTitle').value;
        const description = document.getElementById('reportDescription').value;
        const tags = document.getElementById('reportTags').value
            .split(',')
            .map(tag => tag.trim())
            .filter(tag => tag);

        if (!title) {
            this.showAlert('请输入报告标题', 'warning');
            return;
        }

        try {
            const response = await axios.post(`${this.apiBase}/api/reports/generate`, {
                title,
                description,
                tags
            });

            this.showAlert('实验报告已生成', 'success');
            bootstrap.Modal.getInstance(document.getElementById('reportModal')).hide();
            document.getElementById('reportForm').reset();
            
            // 重新加载报告列表
            this.loadReports();
        } catch (error) {
            console.error('生成报告失败:', error);
            this.showAlert('生成报告失败', 'danger');
        }
    }

    async downloadReport(reportId) {
        try {
            const response = await axios.get(`${this.apiBase}/api/reports/${reportId}`, {
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `report_${reportId}.json`);
            document.body.appendChild(link);
            link.click();
            link.remove();
        } catch (error) {
            console.error('下载报告失败:', error);
            this.showAlert('下载报告失败', 'danger');
        }
    }

    startStatusPolling() {
        setInterval(async () => {
            if (!this.isRunning) {
                const status = await this.getStatus();
                if (status) {
                    this.updateMetrics(status);
                }
            }
        }, 1000);
    }

    showAlert(message, type) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 1050; min-width: 300px;';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 3000);
    }
}

// 全局函数
function startSimulation() {
    demo.startSimulation();
}

function stopSimulation() {
    demo.stopSimulation();
}

function generateReport() {
    demo.generateReport();
}

function submitReport() {
    demo.submitReport();
}

function downloadReport(reportId) {
    demo.downloadReport(reportId);
}

// 初始化应用
const demo = new Sim2SimDemo();
